


//
//  LineSelectViewController.m
//  nncloud
//
//  Created by macfeel on 2019/5/14.
//  Copyright © 2019 macfai. All rights reserved.
//

#import "LineSelectViewController.h"
#import "stationModel.h"

#define leftTableWidth  [UIScreen mainScreen].bounds.size.width * 0.4
#define rightTableWidth [UIScreen mainScreen].bounds.size.width * 0.6
#define ScreenWidth     [UIScreen mainScreen].bounds.size.width
#define ScreenHeight    [UIScreen mainScreen].bounds.size.height


#define leftCellIdentifier  @"leftCellIdentifier"
#define rightCellIdentifier @"rightCellIdentifier"

@interface LineSelectViewController ()<UITableViewDataSource, UITableViewDelegate>


@property (nonatomic, weak) UITableView *leftTableView;

@property (nonatomic, weak) UITableView *rightTableView;


@property (nonatomic,strong)UITextField *textField;

//@property (nonatomic,strong)NSMutableArray *leftArray;
@property (nonatomic,strong)NSArray *leftArray;

@property (nonatomic,strong)NSMutableArray *rightArray;

@property (nonatomic,strong)NSMutableDictionary *dataDict;

@property (nonatomic,copy)NSString *stationName;

@property (nonatomic,copy)NSString *lineName;

@property (nonatomic,copy)NSString *currentLine;

@end

@implementation LineSelectViewController

#pragma mark - 懒加载 tableView -
// MARK: - 左边的 tableView
- (UITableView *)leftTableView {
    
    if (!_leftTableView) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, leftTableWidth, ScreenHeight-64-49-45)];
        
        [self.view addSubview:tableView];
        
        _leftTableView = tableView;
        
        tableView.dataSource = self;
        tableView.delegate = self;
        
        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:leftCellIdentifier];
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.tableFooterView = [[UIView alloc] init];
        
    }
    return _leftTableView;
}

// MARK: - 右边的 tableView
- (UITableView *)rightTableView {
    
    if (!_rightTableView) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(leftTableWidth, 0, rightTableWidth, ScreenHeight-64-49)];
        
        [self.view addSubview:tableView];
        
        _rightTableView = tableView;
        
        tableView.dataSource = self;
        tableView.delegate = self;
        
        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:rightCellIdentifier];
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.tableFooterView = [[UIView alloc] init];
        
    }
    return _rightTableView;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self.navigationItem setItemWithTitle:@"线别选择" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    self.dataDict = [NSMutableDictionary dictionary];
    self.rightArray = [NSMutableArray array];
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightTableView];
    self.view.backgroundColor = kWhiteColor;
    [self loadData];
    
    [self addBottomBuyView];
    UILabel *wholeLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, leftTableWidth-20, 44)];
    wholeLabel.backgroundColor = kWhiteColor;
    wholeLabel.text = @"全部";
    wholeLabel.textAlignment = NSTextAlignmentLeft;
    wholeLabel.textColor = kBlackColor;
    wholeLabel.userInteractionEnabled = YES;
    [self.view addSubview:wholeLabel];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAll)];
    [wholeLabel addGestureRecognizer:tap];
}

///点击全部
-(void)tapAll{
    [NUserModel shareInstance].currentStation = @"";
    [NUserModel shareInstance].currentLine = @"";
    [self.navigationController popViewControllerAnimated:YES];
    [NUserModel shareInstance].currentSelect = YES;
}

- (void)loadData{
    
//    [SVProgressHUD show];
    WeakStament(ws);
    //    [SVProgressHUD show];
    //新需求要求返回五条进行展示
    //    NSDictionary *dic = @{@"size":@(5),@"curPage":@(self.currentPage)};
    //    NSString *url = @"http://biubiu.free.idcfengye.com/DW_jdq/station/stationList";
//    NSString *url = @"/DW_jdq/station/stationList";
    [NNetworkClient postRequestWithBaseUrl:kLineAndStationUrl setParameters:@{} success:^(id responseObject) {
        
        ///装线名和站名
        NSDictionary *tempDict = [NSMutableDictionary dictionary];
        
        if ([responseObject[@"status"]integerValue]==0) {
            NSArray *arr = responseObject[@"data"];
            for (NSDictionary *dict in arr) {
                
                stationModel *model = [stationModel mj_objectWithKeyValues:dict];
                
            ///这个赋值后就可以直接用了 就123行这一行代码就够了
                [tempDict setValue:model.stations forKey:model.line[@"线别"]];
//                [SVProgressHUD dismiss];
                
//                NSMutableArray *jjArray = [NSMutableArray array];
//                for (NSDictionary *sDic in model.stations) {
//                    NSString *zhanming = sDic[@"站名"];
//                    [jjArray addObject:zhanming];
//
//                }
                
//                NSMutableArray *temp = [NSMutableArray array];
//                for (NSDictionary *subDict in model.stations) {
//                    stationModel *subModel = [stationModel mj_objectWithKeyValues:subDict];
//                    [temp addObject:subModel];
//                }
//                model.stations = [temp copy];
//                [self.dataArray addObject:model];
            }
            ////这里拿到这个字典准备传到下个页面
            self.dataDict = [tempDict copy];
            ///左侧表数据源
            self.leftArray = [self.dataDict allKeys];
            [self.leftTableView reloadData];
            ///*********************************************************
            ///拿到第一个元素，然后直接刷出右边表对应的数据
            NSString *leftFirstObject = [self.leftArray firstObject];
            id obj = [self.dataDict objectForKey:leftFirstObject];
            YYLog(@"%@",obj);
            NSArray * array = obj;
            ///实现首次进来将第一条线对应的站数据也加载出来
            for (NSDictionary *dict in array) {
                NSString *staName = dict[@"站名"];
                [self.rightArray addObject:staName];
                YYLog(@"首条线对应的站名%@",self.rightArray);
            }
            [self.rightTableView reloadData];
            ////所有的key 装成数组
//            NSArray *lineArray = [tempDict allKeys];
//            //            YYLog(@"*888所有线名数组:%@",lineArray);
//            NSArray *stationArray = [tempDict allValues];
//            NSMutableArray *singleStationSet = [NSMutableArray array];
            //            YYLog(@"*8888所有站名数组:%@",stationArray);
//            for (int i=0; i<[tempDict allValues].count; i++) {
//                NSString *key = lineArray[i];
//                NSArray *stations = [tempDict objectForKey:key];
//                //                YYLog(@"***88键：%@  值：%@",key,stations);
//                for (NSDictionary *dic in stations) {
//                    NSString *singleStation = dic[@"站名"];
//                    [singleStationSet addObject:singleStation];
//                    //                     YYLog(@"%@",singleStationSet);
//                }
//            }
//            YYLog(@"%@",stationArray);
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
    
}

#pragma mark - tableView 数据源代理方法 -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.leftTableView) return self.leftArray.count;
    return self.rightArray.count?:1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell;
    
    // 左边的 view
    if (tableView == self.leftTableView) {
        
        cell = [tableView dequeueReusableCellWithIdentifier:leftCellIdentifier forIndexPath:indexPath];
//        cell.textLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row];
         cell.textLabel.text = self.leftArray[indexPath.row];
        
        // 右边的 view
    } else {
        
        cell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier forIndexPath:indexPath];
//        cell.textLabel.text = [NSString stringWithFormat:@"第%ld组-第%ld行", indexPath.section, indexPath.row];
        if (self.rightArray.count>indexPath.row) {
        cell.textLabel.text = self.rightArray[indexPath.row];
        }
        
        ///这里需要添加一个标记，放置每次进来都请求
        
    }
    
    return cell;
}


//MARK: - 点击 cell 的代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 选中 左侧 的 tableView
    if (tableView == self.leftTableView) {
        
        NSString *currentLine = self.leftArray[indexPath.row];
        
        self.currentLine = currentLine;
        
        [NUserModel shareInstance].currentLine = currentLine;
        YYLog(@"%@",currentLine);
        ///记得每次把数组清空，不然数据会累计的
        [self.rightArray removeAllObjects];
        NSArray *array = [self.dataDict objectForKey:currentLine];
        for (NSDictionary *dict in array) {
            NSString *station = dict[@"站名"];
            [self.rightArray addObject:station];
        }
        [self.rightTableView reloadData];
    }else{
        
        
        NSString *station = self.rightArray[indexPath.row];
        [NUserModel shareInstance].currentStation = station;
        YYLog(@"%@",station);
        [self.navigationController popViewControllerAnimated:YES];
        
        ///选完之后
        [NUserModel shareInstance].currentSelect = YES;
        
    }
}


#pragma mark - 底条

#define BarHeight 45.f

///添加底部 筛选 新增设备
- (void)addBottomBuyView{
    
    UIButton *cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cartBtn.frame = CGRectMake(0, ScreenHeight-BarHeight-64, ScreenWidth/2-1, BarHeight);
    cartBtn.backgroundColor = kSystemtBlue;
    [cartBtn addTarget:self action:@selector(addLine:) forControlEvents:UIControlEventTouchUpInside];
    [cartBtn setTitle:@"添加线别" forState:UIControlStateNormal];
    [self.view addSubview:cartBtn];
    
    UIButton *gouBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    gouBtn.frame = CGRectMake(ScreenWidth/2, ScreenHeight-BarHeight-64, ScreenWidth/2, BarHeight);
    gouBtn.backgroundColor = kSystemtBlue;
    [gouBtn addTarget:self action:@selector(addStation:) forControlEvents:UIControlEventTouchUpInside];
    [gouBtn setTitle:@"添加站名" forState:UIControlStateNormal];
    [self.view addSubview:gouBtn];
}

///添加线名
- (void)addLine:(UIButton *)btn
{
    [self showAlertWithName:@"请添加线名"];
}

#pragma mark - 添加站名
- (void)addStation:(UIButton *)btn
{

    if (self.currentLine.length>0) {
        
        [self showAlertWithName:@"请在当前线添加站名"];
        
    }else{
        
        [AFToast showText:@"请先选择线别"];
    }
}

#pragma mark - 添加站线
////http://code.cocoachina.com/view/136241
///自适应高度的输入弹出框
-(void)showAlertWithName:(NSString *)name
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:name message:self.currentLine?:@"" preferredStyle:UIAlertControllerStyleAlert];
    self.textField = [UITextField new];
    self.textField.placeholder = @"请输入相关内容";
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = self.textField.placeholder;
        textField.keyboardType = 0;
        self.textField = textField;
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        return ;
    }];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        YYLog(@"jjjjj:%@",self.textField.text);
        //调用添加线名的接口
        if (self.textField.text.length==0) {
            [AFToast showText:@"请输入内容"];
            return ;
        }
        
        if ([name containsString:@"站"]) {
            
            self.stationName = self.textField.text;
            [self addStationWithName:self.textField.text];
            
        }else{
            
            self.lineName = self.textField.text;
            [self addLineWithName:self.textField.text];
            
        }
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark - 添加线名
-(void)addLineWithName:(NSString *)name{
    
    NSDictionary *dict = @{@"lineName":name};
    [NNetworkClient postRequestWithBaseUrl:kAddLineUrl setParameters:dict success:^(id responseObject) {
        YYLog(@"%@",responseObject);
        if ([responseObject[@"status"]integerValue]==0) {
            
            [AFToast showText:@"添加成功"];
            
//            [self.leftTableView reloadData];
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
}

#pragma mark - 添加站名
-(void)addStationWithName:(NSString *)name{
    
    
    NSDictionary *dict = @{@"lineName":self.currentLine?:@"",@"stationName":name,};
    
    [NNetworkClient postRequestWithBaseUrl:kAddStationUrl setParameters:dict success:^(id responseObject) {
        YYLog(@"%@",responseObject);
        if ([responseObject[@"status"]integerValue]==0) {
            [AFToast showText:@"添加成功"];
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
}



@end
